<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-steps :active="step" finish-status="success">
          <el-step title="基本信息"></el-step>
          <el-step title="SKU信息"></el-step>
          <el-step title="保存完成"></el-step>
        </el-steps>
      </el-col>
      <el-col :span="24" v-show="step == 0">
        <el-card class="box-card" style="width: 80%; margin: 20px auto">
          <el-form
            ref="spuBaseForm"
            :model="spu"
            label-width="120px"
            style="margin-right: 60px"
          >
            <el-form-item label="商家名称" prop="title">
              <el-input v-model="spu.title"></el-input>
            </el-form-item>
            <el-form-item label="商家描述" prop="subtitle">
              <el-input v-model="spu.subtitle"></el-input>
            </el-form-item>
            <el-form-item label="所属城市" prop="sortId">
              <el-select
                v-model="cityName"
                placeholder="请选择"
                style="width: 100%"
                @change="changeEvent($event)"
              >
                <el-option
                  v-for="item in cityOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="{
                    id: item.id,
                    value: item.name,
                  }"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商家地址" prop="address">
              <el-input v-model="spu.address" @blur="addressBlur()"></el-input>
            </el-form-item>
            <el-form-item label="所属分类" prop="sortId">
              <el-select
                v-model="spu.sortId"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in sortOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="地图选址" prop="address">
              <div class="map" id="container"></div>
            </el-form-item>
            <el-form-item label="商家图集" prop="images">
              <multi-upload v-model="spu.images"></multi-upload>
            </el-form-item>
            <el-form-item label="商家介绍" prop="decript">
              <multi-upload v-model="spu.decript"></multi-upload>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="generateSkus"
                >下一步：SKU信息</el-button
              >
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
      <el-col :span="24" v-show="step == 1">
        <el-card class="box-card" style="width: 80%; margin: 20px auto">
          <el-table :data="spu.skus" style="width: 100%">
            <el-table-column label="标题" prop="title">
              <template slot-scope="scope">
                <el-input v-model="scope.row.title"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="副标题" prop="skuSubtitle">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuSubtitle"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="价格" prop="price">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price"></el-input>
              </template>
            </el-table-column>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-row>
                  <el-col :span="24">
                    <label style="display: block; float: left"
                      >选择图集 或</label
                    >
                    <multi-upload
                      style="float: left; margin-left: 10px"
                      :showFile="false"
                      :listType="'text'"
                      v-model="uploadImages"
                    ></multi-upload>
                  </el-col>
                  <el-col :span="24">
                    <el-divider></el-divider>
                  </el-col>
                  <el-col :span="24">
                    <el-card
                      style="
                        width: 170px;
                        float: left;
                        margin-left: 15px;
                        margin-top: 15px;
                      "
                      :body-style="{ padding: '0px' }"
                      v-for="(img, index) in spu.images"
                      :key="index"
                    >
                      <img :src="img" style="width: 160px; height: 120px" />
                      <div style="padding: 14px">
                        <el-row>
                          <el-col :span="12">
                            <el-checkbox
                              v-model="scope.row.images[index].imgUrl"
                              :true-label="img"
                              false-label
                            ></el-checkbox>
                          </el-col>
                          <el-col :span="12">
                            <el-tag
                              v-if="scope.row.images[index].defaultImg == 1"
                            >
                              <input
                                type="radio"
                                checked
                                :name="scope.row.title"
                                @change="checkDefaultImg(scope.row, index, img)"
                              />设为默认
                            </el-tag>
                            <el-tag v-else>
                              <input
                                type="radio"
                                :name="scope.row.title"
                                @change="checkDefaultImg(scope.row, index, img)"
                              />设为默认
                            </el-tag>
                          </el-col>
                        </el-row>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="step = 0">上一步</el-button>
          <el-button type="success" @click="submitSkus"
            >下一步：保存商品信息</el-button
          >
        </el-card>
      </el-col>
      <el-col :span="24" v-show="step == 2">
        <el-card class="box-card" style="width: 80%; margin: 20px auto">
          <h1>保存成功</h1>
          <el-button type="primary" @click="addAgian">继续添加</el-button>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import MultiUpload from "@/components/upload/multiUpload";
import BMap from "BMap";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: { MultiUpload, BMap },
  props: {},
  data() {
    return {
      uploadDialogVisible: false,
      uploadImages: [],
      step: 0,
      spu: {
        //要提交的数据
        title: "",
        subtitle: "",
        cityId: "",
        address: "",
        lng: "",
        lat: "",
        sortId: "",
        publishStatus: 0,
        decript: [], //商品详情
        images: [], //商品图集，最后sku也可以新增
        skus: [], //所有sku信息
      },
      inputVisible: [],
      inputValue: [],
      cityName: "",
      cityOptions: [],
      sortOptions: [],
      addressDesc: "",
    };
  },
  //计算属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    uploadImages(val) {
      //扩展每个skus里面的imgs选项
      let imgArr = Array.from(new Set(this.spu.images.concat(val)));

      this.spu.skus.forEach((item, index) => {
        let len = imgArr.length - this.spu.skus[index].images.length; //还差这么多
        if (len > 0) {
          let imgs = new Array(len);
          imgs = imgs.fill({ imgUrl: "", defaultImg: 0 });
          this.spu.skus[index].images = item.images.concat(imgs);
        }
      });
      this.spu.images = imgArr; //去重
    },
  },
  //方法集合
  methods: {
    // 获取城市列表
    getCity() {
      this.$http({
        url: this.$http.adornUrl("/product/city/getAll"),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.cityOptions = data.data;
        } else {
          this.cityOptions = [];
        }
      });
    },

    // 下拉框改变
    changeEvent(event) {
      this.spu.address = "";
      this.spu.cityId = event.id;
      this.addressDesc = event.value + "市";
      this.onMapReady(this.addressDesc);
    },

    // 输入地址
    addressBlur() {
      this.addressDesc += this.spu.address;
      this.onMapReady(this.addressDesc);
    },

    // 展示地图
    onMapReady(value) {
      var that = this;
      var map = new BMap.Map("container");
      if (value) {
        // 初始化地图,设置中心点坐标和地图级别
        map.centerAndZoom(value + this.spu.address, 14);
      } else {
        map.centerAndZoom("北京", 12);
      }
      // 开启鼠标滚轮缩放
      map.enableScrollWheelZoom(true);
      // 添加标注点
      map.addEventListener("click", function (e) {
        if (confirm("是否在此处添加标注点")) {
          that.spu.lng = e.Cg.lng;
          that.spu.lat = e.Cg.lat;
          var marker = new BMap.Marker(new BMap.Point(e.Cg.lng, e.Cg.lat));
          map.addOverlay(marker);
        }
      });
    },
    // 获取分类列表
    getSort() {
      this.$http({
        url: this.$http.adornUrl("/product/sort/getAll"),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.sortOptions = data.data;
        } else {
          this.sortOptions = [];
        }
      });
    },

    addAgian() {
      this.step = 0;
      this.resetSkuData();
    },

    resetSkuData() {
      this.spu = {
        title: "",
        subtitle: "",
        cityId: "",
        address: "",
        lng: "",
        lat: "",
        sortId: "",
        publishStatus: 0,
        decript: [], //商品详情
        images: [], //商品图集，最后sku也可以新增
        skus: [], //所有sku信息
      };
      this.inputVisible = [];
      this.inputValue = [];
      this.cityName = "";
      this.addressDesc = "";
    },

    handlePriceChange(scope, mpidx, e) {
      this.spu.skus[scope.$index].memberPrice[mpidx].price = e;
    },

    showInput(idx) {
      this.inputVisible[idx].view = true;
    },

    checkDefaultImg(row, index, img) {
      //这个图片被选中了，
      row.images[index].imgUrl = img; //默认选中
      row.images[index].defaultImg = 1; //修改标志位;
      //修改其他人的标志位
      row.images.forEach((item, idx) => {
        if (idx != index) {
          row.images[idx].defaultImg = 0;
        }
      });
    },

    // 生成商品数据
    generateSkus() {
      this.step = 1;
      let skus = [];
      //先初始化几个images，后面的上传还要加
      let imgs = [];
      this.spu.images.forEach((img, idx) => {
        imgs.push({ imgUrl: "", defaultImg: 0 });
      });
      skus.push({
        title: this.spu.title,
        price: 0,
        skuSubtitle: this.spu.subtitle,
        images: imgs,
      });
      this.spu.skus = skus;
    },

    // 提交
    submitSkus() {
      this.$confirm("将要提交商品数据，需要一小段时间，是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl("/product/skuinfo/save"),
            method: "post",
            data: this.$http.adornData(this.spu, false),
          }).then(({ data }) => {
            if (data.code == 0) {
              this.$message({
                type: "success",
                message: "新增商品成功!",
              });
              this.step = 2;
            } else {
              this.$message({
                type: "error",
                message: "保存失败，原因【" + data.msg + "】",
              });
            }
          });
        })
        .catch((e) => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {
    this.getSort();
    this.getCity();
    this.onMapReady();
  }, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style>
.map {
  width: 100%;
  height: 600px;
}
</style>